﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.BusinessFlow;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiMinCRMPlugin
{
    [Description("当付款组织不为空且数据来源为OA时，将付款组织默认的银行账号赋值到我方银行账号字段")]
    [HotUpdate]
    public class PayBankEdit : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            var value = (DynamicObject)this.Model.GetValue("FPAYORGID");//付款组织数据包
            //判断付款组织不为空并且数据来源为OA
            if (value != null && Convert.ToString(this.Model.GetValue("F_DEV_DataSrc")) == "OA")
            {
                string FID = value["ID"].ToString();//付款组织编码
                EntryEntity entryEntity = this.View.BusinessInfo.GetEntryEntity("FPAYBILLENTRY");//表体名称
                DynamicObjectCollection entryRows = this.View.Model.GetEntityDataObject(entryEntity);//取得新增加行的行号
                foreach (DynamicObject entryRow in entryRows)//循环单据体遍历
                {
                    DynamicObject FACCOUNTID = entryRow["FACCOUNTID"] as DynamicObject;//我方银行账号
                    int seq = Convert.ToInt32(entryRow["Seq"]);
                    if (FACCOUNTID == null)
                    {
                        string sql = string.Format(@"select a.FBANKACNTID,a.FNUMBER,b.FNAME,c.FNAME as BANKNAME from T_CN_BANKACNT a
                                                    left join T_CN_BANKACNT_L b on a.FBANKACNTID=b.FBANKACNTID
                                                    left join T_BD_BANK_L c on a.FBANKID = c.FBANKID where FUSEORGID='" + FID + "' and F_RDLV_Cost='1' ");
                        DataTable sql_toStirng = DBUtils.ExecuteDataSet(this.Context, sql).Tables[0];
                        if (sql_toStirng.Rows.Count > 0)
                        {
                            this.View.Model.SetItemValueByID("FACCOUNTID", sql_toStirng.Rows[0]["FBANKACNTID"].ToString(), seq - 1);
                            this.View.UpdateView("FACCOUNTID");
                        }
                    }
                }
            }
        }
    }
}
